package com.xyz.ai.service.impl;

import com.xyz.ai.assistant.ChatAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Service
@Slf4j
public class SseService {

    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Autowired
    private ChatAgent chatAgent;
    public SseEmitter createEmitter(String sessionId) {
        SseEmitter emitter = new SseEmitter(3600000L); // 1小时超时

        emitter.onCompletion(() -> emitters.remove(sessionId));
        emitter.onTimeout(() -> emitters.remove(sessionId));
        emitter.onError(e -> emitters.remove(sessionId));

        emitters.put(sessionId, emitter);

        log.info("sessionId {} 连接成功",sessionId);
        // 发送连接成功消息
        sendToClient(sessionId, "connect", "连接成功", "system");

        log.info("sessionId {} sendToClient 连接成功",sessionId);
        return emitter;
    }

    public void sendMessage(String sessionId, String content, String username) {
        // 模拟DeepSeek的流式响应
//        String[] responseParts = {
//                "你好！我是DeepSeek风格的AI助手。",
//                "我看到了你的消息：" + content,
//                "让我来帮你分析这个问题...",
//                "根据我的理解，这是一个很好的问题！",
//                "建议你可以从多个角度思考这个问题。",
//                "希望我的回答对你有帮助！"
//        };

        Flux<String> chat = chatAgent.chat(content);
        chat.doOnNext(response -> {
            // 打印响应日志
            log.info("响应内容2: " + response);
        })
        .delayElements(Duration.ofMillis(500)) // 模拟打字效果
        .subscribeOn(Schedulers.boundedElastic())
        .subscribe(
            response -> {
                char[] chars = response.toCharArray();
                for (int i = 0; i < response.length(); i++) {
                    sendToClient(sessionId, "message", String.valueOf(chars[i]), "deepseek");
                    try {
                        Thread.sleep(100); // 模拟打字效果
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
//                sendToClient(sessionId, "message", response, "deepseek");
            },
            error -> {
                log.error("处理响应时发生错误", error);
            },
            () -> {
                sendToClient(sessionId, "complete", "回答完成", "deepseek");
            }
        );

//        scheduler.schedule(() -> {
//            try {
//                // 模拟流式输出
//                for (int i = 0; i < responseParts.length; i++) {
//                    sendToClient(sessionId, "message", responseParts[i], "deepseek");
//                    Thread.sleep(500); // 模拟打字效果
//                }
//                sendToClient(sessionId, "complete", "回答完成", "deepseek");
//            } catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//            }
//        }, 1000, TimeUnit.MILLISECONDS); // 延迟1秒开始响应
    }

    public void sendToClient(String sessionId, String event, String data, String sender) {
        SseEmitter emitter = emitters.get(sessionId);
        if (emitter != null) {
            try {
                ChatMessage message = new ChatMessage(sender, data, System.currentTimeMillis());
                emitter.send(SseEmitter.event()
                        .name(event)
                        .data(message));
            } catch (IOException e) {
                e.printStackTrace();
                log.info("e",e);
                emitters.remove(sessionId);
            }
        }
    }

    public static class ChatMessage {
        private String sender;
        private String content;
        private long timestamp;
        private String type; // user, assistant, system

        public ChatMessage(String sender, String content, long timestamp) {
            this.sender = sender;
            this.content = content;
            this.timestamp = timestamp;
            this.type = "assistant".equals(sender) ? "assistant" : "user";
        }

        // Getters and setters
        public String getSender() { return sender; }
        public String getContent() { return content; }
        public long getTimestamp() { return timestamp; }
        public String getType() { return type; }
    }
}